﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Core;
using Core.Base;
using System.Windows.Forms;
using System.IO;
using System.Data;
using ERP.BusinessEntities;

namespace MainApp.Modules.Receipt
{
    public class ReceiptModule: BaseModule
    {
        public ReceiptModule()
        {
            this.Name = "Receipt";
            entity = new ReceiptEntity();
            Init();
        }

        #region calculate
        public override void CalcItem_FK_ICProducts_ID(Object objItem, ICProductsInfo Product)
        {
            AppContext.SetProperty(objItem, AppContext.cstFKStock, Product.FK_ICStocks_ID);
            AppContext.SetProperty(objItem, AppContext.cstFKStockUOM, Product.FK_ICStockUOMs_ID);
            AppContext.SetProperty(objItem, AppContext.cstFKTaxCode, Product.FK_TxTaxCodes_InVATID);
            AppContext.SetProperty(objItem, AppContext.cstFUnitPrice, Product.PurchaseUnitPrice);
        }
        #endregion


        public override void Import()
        {
            OpenFileDialog openFileDlg = new OpenFileDialog();
            openFileDlg.Multiselect = false;
            openFileDlg.ShowDialog();

            String strFileName = openFileDlg.FileName;

            if (File.Exists(strFileName) == false) return;

            ExcelClient exClient = new ExcelClient(strFileName);
            exClient.OpenConnection();
            String[] lstSheets = exClient.GetSheetName();
            DataTable dt = exClient.GetAllDataFromSheet(lstSheets[0]);
            foreach (DataRow dr in dt.Rows)
            {
                try
                {
                    
                    
                    String strProductNo = Convert.ToString(dr[0]);
                    ICProductsInfo Product = AppContext.ProductCtrl.GetObjectByNo(strProductNo);
                    if (Product == null) continue;

                    ICReceiptItemsInfo ReceiptItem = new ICReceiptItemsInfo();
                    ReceiptItem.FK_ICProducts_ID = Product.ID;
                    ReceiptItem.FK_TxTaxCodes_ID = Product.FK_TxTaxCodes_InVATID;
                    if (dr[5] != null && dr[5] != DBNull.Value)
                        ReceiptItem.FQty = Convert.ToDouble(dr[5]);

                    if (dr[4] != null && dr[4] != DBNull.Value)
                        ReceiptItem.FUnitPrice = Convert.ToDouble(dr[4]);

                    CalcItem(entity.MainObject, ReceiptItem, "FK_ICProducts_ID");

                    ((ReceiptEntity)entity).lstICReceiptItems.Add(ReceiptItem);
                }
                catch (Exception)
                {

                }

            }

        }

    }
}
